package com.seng.userservice.controller;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.seng.userservice.entity.TbUser;
import com.seng.userservice.service.TbUserService;
import com.seng.userservice.utils.AliOSSUtils;
import com.seng.userservice.vo.TbUserLoginVO;
import com.seng.userservice.vo.TbUserVO;
import com.seng.utilscommon.pwdmd5.MD5Utils;
import com.seng.utilscommon.response.Result;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.List;
import java.util.UUID;

/**
 * <p>
 * 用户表 前端控制器
 * </p>
 *
 * @author seng
 * @since 2020-07-20
 */
@Api(value = "用户管理")
@RestController
@RequestMapping("/userservice/tb-user")
@CrossOrigin
public class TbUserController {

    @Autowired
    private TbUserService tbUserService;

    @Autowired
    private AliOSSUtils aliOSSUtils;

    /**
     * 查询所有用户
     *
     * @return
     */
    @ApiOperation(value = "查询所有用户")
    @GetMapping("/users")
    public Result users() {
        List<TbUser> users = tbUserService.list(null);
        return Result.ok().data("users", users);
    }

    @ApiOperation(value = "逻辑删除用户")
    @DeleteMapping("/{id}")
    public Result delete(@PathVariable("id") Integer id) {
        System.out.println(id);
        boolean delete = tbUserService.removeById(id);
        if (delete) {
            return Result.ok();
        } else {
            return Result.error();
        }
    }

    @ApiOperation(value = "分页查询")
    @GetMapping("/{current}/{size}")
    public Result userPage(@PathVariable("current") Integer current, @PathVariable("size") Integer size) {
        Page<TbUser> page = new Page<>(current, size);
        Page<TbUser> userPage = tbUserService.page(page);
        Long total = userPage.getTotal();
        List<TbUser> records = userPage.getRecords();
        return Result.ok().data("total", total).data("records", records);
    }

    @ApiOperation(value = "根据条件分页查询")
    @PutMapping("/userPageByCon/{current}/{size}")
    public Result userPageBy(@PathVariable("current") Long current, @PathVariable("size") Long size, @RequestBody(required = false) TbUserVO tbUserVO) {
        Page<TbUser> page = new Page<>(current, size);
        QueryWrapper<TbUser> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("deleted", 0);
        if (!StringUtils.isEmpty(tbUserVO.getDepartmentId())) {
            queryWrapper.like("departmentId", tbUserVO.getDepartmentId());
        }
        if (!StringUtils.isEmpty(tbUserVO.getUsername())) {
            queryWrapper.like("username", tbUserVO.getUsername());
        }
        if (!StringUtils.isEmpty(tbUserVO.getNickname())) {
            queryWrapper.like("nickname", tbUserVO.getNickname());
        }
        if (!StringUtils.isEmpty(tbUserVO.getEmail())) {
            queryWrapper.like("email", tbUserVO.getEmail());
        }
        if (!StringUtils.isEmpty(tbUserVO.getSex())) {
            queryWrapper.like("sex", tbUserVO.getSex());
        }
        Page<TbUser> userPage = tbUserService.page(page, queryWrapper);
        Long total = userPage.getTotal();
        List<TbUser> recods = userPage.getRecords();
        return Result.ok().data("total", total).data("recods", recods);
    }

    @ApiOperation(value = "新增用户信息")
    @PostMapping(value = "/addUser")
    public Result addUser(@RequestBody TbUser tbUser) {
        //差一个头像没有设置
        tbUser.setStatus(1);
        //加盐  最后截取0到32位
        tbUser.setSalt(UUID.randomUUID().toString().substring(0, 32));
        tbUser.setType(1);
        //密码先MD5加密再加盐
        tbUser.setPassword(MD5Utils.md5Encryption(tbUser.getPassword(), tbUser.getSalt()));
        //随机生成头像
        tbUser.setAvatar("https://avatars.dicebear.com/api/female/" + tbUser.getUsername() + ".svg");
        boolean user = tbUserService.save(tbUser);
        if (user) {
            return Result.ok().data("add", "ok");
        } else {
            return Result.error();
        }
    }

    @ApiOperation(value = "根据id查询用户")
    @GetMapping("/findById{id}")
    public Result findById(@PathVariable("id") Integer id) {
        TbUser tbUser = tbUserService.getById(id);
        if (StringUtils.isEmpty(tbUser)) {
            throw new RuntimeException("用户没找到");
        }
        return Result.ok().data("tbUser", tbUser);
    }

    @ApiOperation(value = "根据id进行修改")
    @PutMapping("/updateById")
    public Result updateById(@RequestBody TbUser tbUser) {
        System.out.println(tbUser.toString());
        boolean updatebyId = tbUserService.updateById(tbUser);
        //System.out.println(tbUserService.getById(tbUser.getId()));
        /*if (!updatebyId) {
            throw new RuntimeException("用户没找到");
        }*/
        return Result.ok().data("updatebyId", updatebyId);
    }

    @ApiOperation(value = "导出学生信息")
    @GetMapping(value = "/export")
    public void exportStudentInfoExcel(HttpServletResponse response) throws IOException {
        tbUserService.exportStudentInfoExcel(response);
    }

    @ApiOperation(value = "上传图片文件到alibaba的OSS")
    @PostMapping("/uploadImgFile")
    public String uploadImgFile(MultipartFile file) {
        aliOSSUtils.uploadImgFile(file);
        System.out.println("上传成功");
        return "success";
    }
}
